from jose import jwt
import time

SECRET_KEY = "最喜欢的一集"
ALGORITHM = "HS256"

async def create_jwt(data: dict) -> str:
    # 只包含必要字段 + 短过期时间
    payload = {
        "sub": str(data["sub"]),
        "lv": str(data["lv"]),
        "exp": int(time.time()) + 12000
    }
    return jwt.encode(payload, SECRET_KEY, algorithm=ALGORITHM)

async def verify_jwt(token: str) -> dict:
    try:
        res = jwt.decode(token, SECRET_KEY, algorithms=ALGORITHM)
        return res
    except:
        print("请求错误")
        return {}


async def check_token_validity(token: str) -> bool:
    tokens = await verify_jwt(token)
    if tokens:
        if tokens["lv"] == "4":
            print("token权限校验成功")
            return True
    else:
        print("token权限校验失败 ")
        return False

async def check_token_outTime(token: str) -> bool:
    payload = await verify_jwt(token)
    if payload["exp"] > int(time.time()):
        print("Token未过期 ")
        return True
    else:
        print("Token过期 ")
        return False